package com.affablebeans.listener;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;

import com.affablebeans.model.DbContext;

/**
 * 
 * @author Bora SAYINER
 * @since Jan 31, 2015 4:14:24 PM
 * @version 1.0.0
 */
public class ApplicationListener implements ServletContextListener {

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		try {
			Context initContext = new InitialContext();
			Context context = (Context) initContext.lookup("java:comp/env");
			DataSource dataSource = (DataSource) context.lookup("jdbc/affablebean");
			DbContext dbContext = new DbContext(dataSource);
			sce.getServletContext().setAttribute("dbContext", dbContext);
			sce.getServletContext().setAttribute("categories", dbContext.getCategories().getAllCategories());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}

}
